package edu.upc.fib.lamsandroid.server.web.controller;

import edu.upc.fib.lamsandroid.server.api.model.Activity;
import edu.upc.fib.lamsandroid.server.api.response.activity.GetByIdResponse;
import edu.upc.fib.lamsandroid.server.lams.Util;
import edu.upc.fib.lamsandroid.server.manager.ActivityManager;
import org.apache.commons.io.IOUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

@Controller
public class ActivityController {

    @Autowired
    ActivityManager activityManager;

    @RequestMapping(value = "/activity/getById", method = RequestMethod.POST)
    public @ResponseBody
    GetByIdResponse getById(
            @RequestParam("id") Long id) {

        GetByIdResponse response = new GetByIdResponse(activityManager.fetchById(id));

        for (Activity activity : response.getPayload()) {
            if(activity.getToolContent() != null) {
                String json = "{}";

                ObjectMapper mapper = new ObjectMapper();
                try {
                    json = mapper.writeValueAsString(activity.getToolContent().getData());
                } catch (IOException e) {
                    System.out.println(e.toString());
                }

                activity.getToolContent().getData().setJson(json);
            }
        }

        return response;
    }

    @RequestMapping(value = "/activity/getFileByNodeId/{node_id}", method = RequestMethod.GET)
    public @ResponseBody void getFileByNodeId(
            @PathVariable("node_id") String nodeId,
            HttpServletResponse response) {
        try {
            // get your file as InputStream
            File file = Util.getContentRepositoryFile(nodeId);
            System.out.println("Reading from: " + file.getAbsolutePath());
            InputStream is = new FileInputStream(file);
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();
        } catch (IOException ex) {
            System.out.println("Error writing file to output stream. nodeId was '" + nodeId + "' ("+Util.getContentRepositoryFile(nodeId)+")");
            //log.info("Error writing file to output stream. Filename was '" + fileName + "'");
            throw new RuntimeException("IOError writing file to output stream");
        }

    }

    @RequestMapping(value = "/activity/getFileBySecureURL/**", method = RequestMethod.GET)
    public @ResponseBody void getFileBySecureURL(HttpServletRequest request, HttpServletResponse response) {
        final String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        final String restOfPath = path.replace("/activity/getFileBySecureURL/", "");
        try {
            // get your file as InputStream
            File file = Util.getSecureFile("/" + restOfPath);
            System.out.println("Reading from: " + file.getAbsolutePath());
            InputStream is = new FileInputStream(file);
            // copy it to response's OutputStream
            IOUtils.copy(is, response.getOutputStream());

            response.flushBuffer();
        } catch (IOException ex) {
            System.out.println("Error writing file to output stream. restOfPath was '" + restOfPath);
            //log.info("Error writing file to output stream. Filename was '" + fileName + "'");
            throw new RuntimeException("IOError writing file to output stream");
        }
    }
}
